package cn.well.cloud.core.auth;

import static cn.well.cloud.base.consts.ConstantsContext.getJwtSecretExpireSec;
import static cn.well.cloud.base.consts.ConstantsContext.getTokenHeaderName;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.collection.CollectionUtil;
import cn.well.cloud.base.auth.context.LoginContextHolder;
import cn.well.cloud.base.auth.jwt.JwtTokenUtil;
import cn.well.cloud.base.auth.jwt.payload.JwtPayLoad;
import cn.well.cloud.base.auth.model.LoginUser;
import cn.well.cloud.base.auth.service.AuthService;
import cn.stylefeng.roses.core.util.HttpContext;
import cn.stylefeng.roses.core.util.SpringContextHolder;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.well.cloud.core.auth.cache.CacheManager;
import cn.well.cloud.modular.model.factory.AppAccount;
import cn.well.cloud.modular.model.factory.UserFactory;

/**
 * 授权实现类
 * 2019年12月24日
 * @author wison
 *
 */
@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private CacheManager cacheManager;

    public static AuthService me() {
        return SpringContextHolder.getBean(AuthService.class);
    }

    @Override
    public String login(String username, String password) {
        //TODO 账号验证，密码验证
        return login(username);
    }

    @Override
    public String login(String username) {
        //TODO key的作用
        String key = ToolUtil.getRandomString(6);
        
        JwtPayLoad payLoad = new JwtPayLoad(Long.parseLong(username), null, key);
        //创建token
        String token = JwtTokenUtil.generateToken(payLoad);
        //创建登录缓存
        cacheManager.createSession(token, user(username));
        
        return token;
    }

    @Override
    public void addLoginCookie(String token) {
        //创建cookie
        Cookie authorization = new Cookie(getTokenHeaderName(), token);
        authorization.setMaxAge(getJwtSecretExpireSec().intValue());
        authorization.setHttpOnly(true);
        authorization.setPath("/");
        HttpServletResponse response = HttpContext.getResponse();
        response.addCookie(authorization);
    }

    @Override
    public void logout() {
        String token = LoginContextHolder.getContext().getToken();
        logout(token);
    }

    @Override
    public void logout(String token) {
        //删除Auth相关cookies
        Cookie[] cookies = HttpContext.getRequest().getCookies();
        for (Cookie cookie : cookies) {
            String tokenHeader = getTokenHeaderName();
            if (tokenHeader.equalsIgnoreCase(cookie.getName())) {
                Cookie temp = new Cookie(cookie.getName(), "");
                temp.setMaxAge(0);
                HttpContext.getResponse().addCookie(temp);
            }
        }
    }

    @Override
    public LoginUser user(String account) {
        AppAccount user = new AppAccount();
        LoginUser loginUser = UserFactory.createLoginUser(user);
        return loginUser;
    }

    @Override
    public List<String> findPermissionsByRoleId(Long roleId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean check(String[] roleNames) {
        LoginUser user = LoginContextHolder.getContext().getUser();
        if (null == user) {
            return false;
        }
        ArrayList<String> objects = CollectionUtil.newArrayList(roleNames);
        String join = CollectionUtil.join(objects, ",");
        if (LoginContextHolder.getContext().hasAnyRoles(join)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean checkAll() {
        // TODO Auto-generated method stub
        return false;
    }

  

 

}
